package org.dromara.tearoom.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.web.core.BaseController;
import org.dromara.tearoom.domain.bo.*;
import org.dromara.tearoom.domain.vo.*;
import org.dromara.tearoom.service.ITerOrderService;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * 订单
 * 前端访问路由地址为:/tearoom/order
 *
 * @author xch
 * @date 2025-03-29
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/order")
public class TerOrderController extends BaseController {

    private final ITerOrderService terOrderService;



    /**
     * 后台管理系统_查询订单列表
     */
    @SaCheckPermission("tearoom:order:list")
    @GetMapping("/list")
    public TableDataInfo<TerOrderVo> list(TerOrderBo bo, PageQuery pageQuery) {
        return terOrderService.queryPageList(bo, pageQuery);
    }
    /**
     * 首页查询
     */
    @SaCheckPermission("tearoom:order:query")
    @GetMapping("/queryOrderCount")
    public R<TerOrderDayVo> queryOrderCount(@ModelAttribute TerUserCountTotalBo tbo)  {
        return  R.ok(terOrderService.queryOrderCount(tbo));
    }
    /**
     * 首页退款金额查询
     */
    @SaCheckPermission("tearoom:order:query")
    @GetMapping("/queryRefund")
    public R<TerOrderDayVo> queryRefund(@ModelAttribute TerUserCountTotalBo tbo)  {
        return  R.ok(terOrderService.queryRefund(tbo));
    }

    /**
     * 首页余额支付查询
     */
    @SaCheckPermission("tearoom:order:query")
    @GetMapping("/queryBanlcPay")
    public R<TerOrderDayVo> queryBanlcPay(@ModelAttribute TerUserCountTotalBo tbo)  {
        return  R.ok(terOrderService.queryBalancePay(tbo));
    }

    /**
     * 小程序_新增回调查询
     */
    @GetMapping("/qyCallback/{id}")
    public R<TerOrderVo> qyCallback(@NotNull(message = "主键不能为空")
                                        @PathVariable("id") String id) {
        return R.ok(terOrderService.queryById(id));
    }
    /**
     * 后台管理系统_导出订单列表
     */
    @SaCheckPermission("tearoom:order:export")
    @Log(title = "订单数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TerOrderBo bo, HttpServletResponse response) {
        List<TerOrderExportVo> list = terOrderService.queryListExcel(bo);
        ExcelUtil.exportExcel(list, "订单数据", TerOrderExportVo.class, response);
    }

    /**
     * 后台管理系统_获取订单详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("tearoom:order:query")
    @GetMapping("/{id}")
    public R<TerOrderVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable("id") String id) {
        return R.ok(terOrderService.queryById(id));
    }


    @SaCheckPermission("tearoom:regionalInfo:edit")
    @Log(title = "修改异常订单状态", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> updateStatus(@Validated(EditGroup.class) @RequestBody TerOrderBo bo) {
        return toAjax(terOrderService.updateStatus(bo));
    }
    /**
     * 获取订单详细信息
     *
     * @param openIdBo
     */
    @GetMapping("/queryOrder")
    public R<List<TerOrderRoomVo>> queryOrder(@ModelAttribute TerOderOpenIdBo  openIdBo) {
        return R.ok(terOrderService.queryByOpenId(openIdBo));
    }

    /**
     * 获取订单详细信息
     *
     * @param bo
     * @param pageQuery
     */
    @GetMapping("/appPage")
    public TableDataInfo<TerOrderVo> appPage(TerOrderBo bo, PageQuery pageQuery) {
        return terOrderService.queryAppPageList(bo, pageQuery);
    }

    /**
     * 小程序_时间轴占用查询
     */

    @GetMapping("/wechat/queryTimelist")
    public R<List<Map<String, Integer>>> queryTimelist(@ModelAttribute TerOrderTimeBo bo)  {
        return  R.ok(terOrderService.queryTimelist(bo));
    }

    /**
     * 小程序_新增订单
     */
    @RepeatSubmit()
    @Log(title = "订单新增", businessType = BusinessType.INSERT)
    @PostMapping("/addOrder")
    public R<TerOrderVo> addOrder(@Validated(AddGroup.class) @RequestBody TerOrderBo bo) {
        TerOrderVo vo =null;
        try {
            vo=  terOrderService.insertByBo(bo);
            return R.ok(vo);
        }catch(RuntimeException e) {
            return R.warn(e.getMessage());
        }
    }

    /**
     * 小程序_订单支付
     */
    @Log(title = "订单支付", businessType = BusinessType.UPDATE)
    @PostMapping("/payOrder")
    public WxSignParam payOrder(@Validated(AddGroup.class) @RequestBody TerPayOrderBo bo) {
        return terOrderService.payOrder(bo);
    }
    /**
     * 小程序_支付回调修改
     */
    @Log(title = "支付回调", businessType = BusinessType.UPDATE)
    @PostMapping("/payCallBack")
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TerOrderBo bo) {
        return toAjax(terOrderService.updateOrder(bo));
    }

    @PostMapping("/wechat/payNotify")
    public R<Void> payNotify(HttpServletRequest request) {
        return toAjax(terOrderService.payNotify(request));
    }
    /**
     * 小程序_立即使用
     */
    @RepeatSubmit()
    @Log(title = "密钥使用", businessType = BusinessType.UPDATE)
    @PostMapping("/useKey")
    public UseKeyParam useKey(@Validated(AddGroup.class) @RequestBody TerUseKeyBo bo) {
        return terOrderService.useKey(bo);
    }

    /**
     * 小程序_密钥获取
     */
    @RepeatSubmit()
    @Log(title = "密钥获取", businessType = BusinessType.UPDATE)
    @PostMapping("/getKey")
    public UseKeyParam getKey(@Validated(AddGroup.class) @RequestBody TerUseKeyBo bo) {
        return terOrderService.getKey(bo);
    }

    @RepeatSubmit()
    @Log(title = "订单退回", businessType = BusinessType.UPDATE)
    @PostMapping("/orderRefund")
    public R<Void> orderRefund(@Validated(EditGroup.class) @RequestBody TerOrderBo bo) {
        try {
            return toAjax(terOrderService.orderRefund(bo));
        }catch(RuntimeException e) {
            return R.warn(e.getMessage());
        }
    }

    /**
     * 首页订单数量统计
     * @param start
     * @param end
     * @return
     */
    @GetMapping("/stats")
    public R<OrderStatDTO> getOrderStats(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDate start,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDate end) {

        if (start.isAfter(end)) {
            throw new ServiceException("开始时间不能晚于结束时间");
        }
        return R.ok(terOrderService.getOrderStats(start, end));
    }


    @SaCheckPermission("tearoom:regionalInfo:edit")
    @Log(title = "修改异常订单状态", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/replaceOrder")
    public R<Void> replaceOrder(@Validated(EditGroup.class) @RequestBody TerOrderBo bo) {
        try {
            return toAjax(terOrderService.replaceOrder(bo));
        }catch(RuntimeException e) {
            return R.warn(e.getMessage());
        }
    }
}
